import type { UploadProps } from 'antd';
import { Button, message, Upload, Input, Form } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import axios from 'axios';
import { useState } from 'react';
let data: FormData = new FormData()

const props: UploadProps = {
  name: 'file',
  accept: '.html',
  beforeUpload: () => {
    return false
  },
  onChange(info: any) {
    if (info.file.type === "text/html") {
      data.append('htmlFile', info.file)
    }
  }
};
const checkType = (fileList: Array<{ name: string }>) => {
  let HtmlTyep = false;
  for (let value of fileList) {
    if (value.name.includes('.html')) {
      HtmlTyep = true
    } 
  }
  return HtmlTyep
}
function Clear() {
  const [form] = Form.useForm()
  const [messageApi, contextHolder] = message.useMessage();
  const [textMsg, setTextMsg] = useState<string>()
  const submit = () => {
    form.validateFields().then((values) => {
      data.append('attrs', values.attrs)
      axios.post('/api/clear', data,
        {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        .then(res => {
          form.resetFields()
          data = new FormData()
          if (res.data.code !== 200) {
            messageApi.error(res.data.msg)
          } else {
            messageApi.success(res.data.msg)
            setTextMsg(res.data.data)
          }
        })
    })

  }
  const copy = () =>{
    if(!textMsg){
      messageApi.error("请先提交")
      return
    }else{
      const htmlBody = document.createElement('body');
      htmlBody.innerHTML = textMsg;
      
      if (navigator.clipboard &&navigator.clipboard.writeText) {
        // 使用async/await处理异步操作
        async function copyText() {
          try {
            await navigator.clipboard.writeText((htmlBody.querySelector("#root")?.outerHTML)as string);
            messageApi.success("文本已成功复制到剪贴板")
          } catch (err) {
            messageApi.error('无法复制到剪贴板:'+err)
          }
        }
        copyText();
      } else {
        messageApi.error("您的浏览器不支持该复制功能，请使用现代浏览器")
      }
    }
    
  }
  return (
    <>
      {contextHolder}
      <Form form={form} layout="horizontal" style={{ width: '300px' }}>
        <Form.Item name="file" label="文件" validateTrigger="onBlur" rules={[{ required: true }, () => ({
          validator(_, value: any) {
            if (Array.isArray(value && value.fileList) && value.fileList.length <= 0) {
              return Promise.resolve()
            }
            if (checkType(value.fileList)) {
              return Promise.resolve()
            } else {
              return Promise.reject(new Error('必须同时html文件以及需要清除的属性'));
            }

          },
        })]}>
          <Upload {...props} maxCount={2} onChange={props.onChange}>
            <Button icon={<UploadOutlined />}>上传</Button>
          </Upload>
        </Form.Item>
        <Form.Item name="attrs" label="属性字段" validateTrigger="onBlur" rules={[{ required: true}]}>
          <Input placeholder='请输入需要清除的属性'></Input>
        </Form.Item>
        <Form.Item>
          <Button onClick={submit}>提交</Button>
          {/* <Button onClick={copy} style={{marginLeft:"20px"}}>一键复制</Button> */}
        </Form.Item>
      </Form>
      <Input.TextArea value={textMsg} disabled rows={50}></Input.TextArea>

    </>
  )
}

export default Clear
